package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;


@Controller
@RequestMapping("/cargo/factory")
@Slf4j
public class FactoryController extends BaseController {

    @Reference
    private FactoryService factoryService;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行合同管理列表查询开始...");
        //构造条件对象

        FactoryExample factoryExample = new FactoryExample();
        factoryExample.setOrderByClause("create_time desc");
        PageInfo<Factory> pageInfo = factoryService.findByPage(factoryExample,pageNum,pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/factory/factory-list";
    }

    /**
     * 2. 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String save(Factory factory) {
        return "cargo/factory/factory-add";
    }

    /**
     * 3. 添加购销合同或修改购销合同
     */
    @RequestMapping("/edit")
    public String edit(Factory factory) {
        if (StringUtils.isEmpty(factory.getId())){
            //设置创建时间
            factory.setCreateTime(new Date());
            factoryService.save(factory);
        }else{
            factoryService.update(factory);
        }
        return "redirect:/cargo/factory/list";
    }


    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model) {
        Factory factory = factoryService.findById(id);
        model.addAttribute("factory",factory);
        return "cargo/factory/factory-update";
    }

    /**
     * 5. 删除
     */
    @GetMapping("/delete")
    public String delete(String id) {
        factoryService.delete(id);
        return "redirect:/cargo/factory/list";
    }


}
